import type { Ref } from 'vue'
import { onMounted, onUnmounted } from 'vue'

// 确定是哪个区域外侧
const useClickOutside = (elementRef: Ref<undefined | HTMLElement>, callback: (e: MouseEvent) => void) => {
    const handler = (e: MouseEvent) => {
        if (elementRef.value && e.target) {
            //    当点击到容器外侧时
            if (!elementRef.value.contains(e.target as HTMLElement)) {
                callback(e)
            }
        }
    }
    onMounted(() => {
        document.addEventListener('click', handler)
    })

    onUnmounted(() => {
        document.removeEventListener('click', handler)
    })
}

export default useClickOutside

